//
//  DeviceManagerViewController.m
//  Kids
//
//  Created by tengfei on 14/11/22.
//  Copyright (c) 2014年 90's Technology Co.Ltd. All rights reserved.
//

#import "DeviceManagerViewController.h"
#import "DeviceEditView.h"
#import "UIImage+UIImageScale.h"

#import "WatchAddRequestData.h"
#import "WatchAddResponseData.h"
#import "RequestFactory.h"
#import "AccountInfo.h"

#import "WatchListRequestData.h"
#import "WatchListResponseData.h"
#import "NSString+md5.h"

#import "SVProgressHUD.h"
#import "UIImageView+WebCache.h"
@interface DeviceManagerViewController ()<DeviceEditDelegate,UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@property (nonatomic, strong) NSMutableArray* onlineArray;
@property (nonatomic, strong) NSMutableArray* outlineArray;
@property (nonatomic, strong) UIBarButtonItem * addDeviceBarButton;
@property (nonatomic, strong) UITableView * tableView;
@property (nonatomic,strong) UIImage * image;
@end

@implementation DeviceManagerViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.onlineArray = [[NSMutableArray alloc] initWithCapacity:0];
    self.outlineArray = [[NSMutableArray alloc] initWithCapacity:0];
    
    self.tableView = [[UITableView alloc]initWithFrame:[[UIScreen mainScreen]bounds] style:UITableViewStyleGrouped];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    
    self.addDeviceBarButton = ({
        UIButton * button = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 44, 44)];
        [button setImage:[UIImage imageNamed:@"plus_button"] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(addDeviceBarButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        UIBarButtonItem * addDeviceButton = [[UIBarButtonItem alloc]initWithCustomView:button];
        addDeviceButton;
    });
    
    self.navigationItem.rightBarButtonItem = self.addDeviceBarButton;
    
    self.deviceEditView = [[DeviceEditView alloc]init];
    self.deviceEditView.delegate=self;
    [self refreashWatchData];
}
-(void)addDeviceBarButtonClick:(UIButton *)button{
    self.deviceEditView.editer = NO;
    [self.deviceEditView show];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}
- (void)refreashWatchData
{
    [self.onlineArray removeAllObjects];
    [self.outlineArray removeAllObjects];
    
    WatchListRequestData* data = [[WatchListRequestData alloc] init];
    
    AccountInfo * info =     [AccountInfo shareInstance];
    
    NSAssert(info.phone.length>0, @"number must not be nil");
    NSAssert(info.password.length > 0, @"password not be nil");
    
    data.phone = info.phone;
    data.password = [info.password md5];
    
    WatchListResponseData* responseData = [[WatchListResponseData alloc] init];
    
    [RequestFactory requestWithRequestData:data forResponseData:responseData complete:^(ResponseData* responseData, NSError* error) {
        NSLog(@"%@",responseData.info);
        NSLog(@"%ld",(unsigned long)[[(WatchListResponseData *)responseData modelList] count]);
        NSArray * array = [[NSArray alloc]initWithArray:[(WatchListResponseData *)responseData modelList]];
        if(array.count==0){
            [SVProgressHUD showImage:nil status:@"没有关联设备"];
        }
        for (WatchModel * model in array) {
            if([model.wstate isEqualToString:@"1"]){
                [self.onlineArray addObject:model];
            }else{
                [self.outlineArray addObject:model];
            }
        }
        [self.tableView reloadData];
    }];
}
#pragma mark -

- (NSInteger)numberOfSectionsInTableView:(UITableView*)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section
{
    if(section==0){return self.onlineArray.count;}
    
    if(section==1){return  self.outlineArray.count;}
    return 0;
}
- (CGFloat)tableView:(UITableView*)tableView heightForHeaderInSection:(NSInteger)section
{
    return 30;
}

- (NSString*)tableView:(UITableView*)tableView titleForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return @"在线";
    }
    else {
        return @"离线";
    }
}
- (CGFloat)tableView:(UITableView*)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath
{
    return 70;
}
- (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath
{
    static NSString* cellIdentifier = @"cell";

    UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    if (indexPath.section == 0) {
        WatchModel * model = [self.onlineArray objectAtIndex:indexPath.row];
        cell.textLabel.text = model.wname;
        cell.detailTextLabel.text = [NSString  stringWithFormat:@"号码:%@",model.wphone];
        cell.imageView.image = [UIImage imageNamed:@"yellowchips"];

    }
    else {
        WatchModel * model = [self.outlineArray objectAtIndex:indexPath.row];
        cell.textLabel.text = model.wname;
        cell.detailTextLabel.text = [NSString  stringWithFormat:@"号码:%@",model.wphone];
        NSString * imagePath  =  [NSString stringWithFormat:@"114.215.169.134/chip/%@",model.wimage];
        [cell.imageView sd_setImageWithURL:[NSURL URLWithString:imagePath] placeholderImage:[UIImage imageNamed:@"photo_size"]];
       
    }
     return cell;
}
- (void)tableView:(UITableView*)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath*)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
    }
}
- (BOOL)tableView:(UITableView*)tableView canEditRowAtIndexPath:(NSIndexPath*)indexPath
{
    return YES;
}
- (UITableViewCellEditingStyle)tableView:(UITableView*)tableView editingStyleForRowAtIndexPath:(NSIndexPath*)indexPath
{
    return UITableViewCellEditingStyleDelete;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    WatchModel * model;
    
    if(indexPath.section==0){
        model =[[self onlineArray] objectAtIndex:indexPath.row];
    }else if(indexPath.section==1){
        model = [[self outlineArray]objectAtIndex:indexPath.row];
    }
    self.deviceEditView.model= model;
    self.deviceEditView.editer = YES;
    [self.deviceEditView show];
}
#pragma mark -
-(void)didSelectedSubmitButtonInDeviceEditView:(DeviceEditView *)editView{
    
    WatchAddRequestData * requestData= [[WatchAddRequestData alloc]init];
    requestData.imei = editView.model.wimei;
    requestData.pphone = [AccountInfo shareInstance].phone;
    requestData.ppassword = [[AccountInfo shareInstance].password md5];
    requestData.wphone = editView.phoneTextField.text;
    requestData.name = editView.nameTextField.text;
    
    UIImage * im = editView.headerImage;
    NSData * data = UIImageJPEGRepresentation(im, 1.0);
    NSString * base64 = [data base64EncodedStringWithOptions:0];
    requestData.image = base64;
    
    WatchAddResponseData * response = [[WatchAddResponseData alloc]init];
    
    [RequestFactory requestWithRequestData:requestData forResponseData:response complete:^(ResponseData *responseData, NSError *error) {
        if(responseData){
            [SVProgressHUD showImage:nil status:responseData.info];
            [self refreashWatchData];
        }
    }];
}
-(void)didSelectedCancelButtonInDeviceEditView:(DeviceEditView *)editView{

}
- (void)didSelectedEditButtonInDeviceEditView:(DeviceEditView *)editView
{
    UIActionSheet* sheet = [[UIActionSheet alloc] initWithTitle:@"" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"拍照" otherButtonTitles:@"从相册选择", nil];
    [sheet showInView:[UIApplication sharedApplication].keyWindow];
}
#pragma mark -
- (void)actionSheet:(UIActionSheet*)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    UIImagePickerControllerSourceType sourceType;
    if (buttonIndex == 0) {
        sourceType = UIImagePickerControllerSourceTypeCamera;
        if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        }
    }else if (buttonIndex == 1) {
        sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    }else {
        return;
    }
        //创建图像选取控制器
    UIImagePickerController* imagePickerController = [[UIImagePickerController alloc] init];
        //设置图像选取控制器的来源模式为相机模式
    imagePickerController.sourceType = sourceType;
        //允许用户进行编辑
    imagePickerController.allowsEditing = YES;
        //设置委托对象
    imagePickerController.delegate = self;
    if (sourceType == UIImagePickerControllerSourceTypeCamera) {
        imagePickerController.cameraDevice = UIImagePickerControllerCameraDeviceRear;
    }
        //以模视图控制器的形式显示
    [self.deviceEditView dismiss];
    [self presentViewController:imagePickerController animated:YES completion:nil];
}

#pragma mark - UIImagePickerControllerDelegate 
#pragma 拍照选择照片协议方法

- (void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary*)info
{
    [UIApplication sharedApplication].statusBarHidden = NO;
    
    NSString* mediaType = [info objectForKey:UIImagePickerControllerMediaType];
    
    if ([mediaType isEqualToString:@"public.image"]) {
        
        UIImage* originImage = [info objectForKey:UIImagePickerControllerEditedImage];
        
        UIImage * headerImage = [originImage scaleToSize:CGSizeMake(200, 200)];
        
        self.deviceEditView.headerImage = headerImage;
        
        [picker dismissViewControllerAnimated:YES completion:^{
            [self.deviceEditView show];
        }];
    }
}
@end
